package restlet.description.convert;

import org.softmed.rest.config.Application;
import org.softmed.rest.config.Handler;
import org.softmed.rest.config.HttpMethod;
import org.softmed.rest.config.MimeTypeHandler;
import org.softmed.rest.config.Module;
import org.softmed.rest.config.Parameter;
import org.softmed.rest.config.Resource;

import com.thoughtworks.xstream.XStream;

public class ConfigurationXMLConverter {
	XStream streamer = new XStream();

	public ConfigurationXMLConverter() {

		streamer.useAttributeFor("uri", String.class);
		streamer.useAttributeFor("active", boolean.class);
		streamer.useAttributeFor("name", String.class);
		streamer.useAttributeFor("value", String.class);
		streamer.useAttributeFor("targetUri", Resource.class);
		streamer.useAttributeFor("mimeType", MimeTypeHandler.class);

		streamer.alias("application", Application.class);

		streamer.alias("parameter", Parameter.class);

		streamer.alias("handler", Handler.class);

		streamer.alias("mime-type-handler", MimeTypeHandler.class);
		streamer.aliasField("mime-type", MimeTypeHandler.class, "mimeType");

		streamer.alias("http-method", HttpMethod.class);
		streamer.aliasField("mime-type-handlers", HttpMethod.class,
				"mimeTypeHandlers");

		streamer.alias("resource", Resource.class);
		streamer.aliasField("target-uri", Resource.class, "targetUri");

		streamer.alias("module", Module.class);

		streamer.omitField(Application.class, "id");
		streamer.omitField(Module.class, "id");
		streamer.omitField(Resource.class, "id");
		streamer.omitField(HttpMethod.class, "id");
		streamer.omitField(MimeTypeHandler.class, "id");
		streamer.omitField(Handler.class, "id");
		streamer.omitField(Parameter.class, "id");

		// Remove after tests are done
		// streamer.alias("Wtf", Wtf.class);

	}

	public String toXML(Object object) {
		return streamer.toXML(object);
	}

	public Object fromXML(String xml) {
		Object object = streamer.fromXML(xml);
		if (object instanceof RecoverFromSerialization)
			((RecoverFromSerialization) object).recoverFromSerialization();

		return object;
	}

}
